package main

import (
  "io"
  "os"
  "fmt"
  "net/http"
)

type RespBodyList struct {
  Code   int       `json:"code"`
  Error  string    `json:"error"`
  Certs  []Cert    `json:"certs"`  // Cert -> types.go
  Marker string    `json:"marker"`
}

func handleList(cfg *CLI) {
  var printedHeader bool //是否打印表头
  loopListRequest(cfg, func(certs []Cert) {
    if len(certs) == 0 {
      return
    }
    if !printedHeader {
      certs[0].PrintxHeader()
      printedHeader = true
    }
    for i := range certs {
      certs[i].Printx()
    }
  })
}

func loopListRequest(cfg *CLI, handlePage func([]Cert)) {
  var marker string
  for {
    resp, err := sendListRequest(cfg, marker)
    if err != nil {
      fmt.Fprintf(os.Stderr, "failed to send http request: %v\n", err)
      os.Exit(ExitRequestError)
    }

    body, err := io.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
      fmt.Fprintf(os.Stderr, "read body failed: %v\n", err)
      os.Exit(ExitIoError)
    }

    if cfg.Verbose || resp.StatusCode != 200 {
      dumpJson(body)
    }
    if resp.StatusCode != 200 {
      os.Exit(ExitOtherError)
    }

    r, err := parseJSONResponse[RespBodyList](body)
    if err != nil {
      fmt.Fprintf(os.Stderr, "[%s]\nparse error: %v\n", string(body), err)
      os.Exit(ExitUnmarshalError)
    }

    if len(r.Certs) == 0 {
      break // 实测发现七牛云 CDN 获取证书列表接口行为与文档中的行为表现不一致，marker 一直会有, 但最后 certs 会是个空数组
    }

    handlePage(r.Certs)

    marker = r.Marker
    if marker == "" {  //保留文档中的行为: 没有 mark 意味着没有后继数据
      break
    }
  }
}

func sendListRequest(cfg *CLI, marker string) (*http.Response, error) { //GET /sslcert?marker=<Marker>&limit=<limit>
  return sendQiNiuRequest(cfg, http.MethodGet, "/sslcert", "marker=" + marker, nil)
}
